package com.qianclass.talklive.app.activity;

import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Base64;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.BitmapCallback;
import com.pili.pldroid.player.PLMediaPlayer;
import com.qianclass.talklive.R;
import com.qianclass.talklive.app.adapter.ChatHistoryAdapter;
import com.qianclass.talklive.app.bean.FileInfo;
import com.qianclass.talklive.app.bean.RecordIMInfo;
import com.qianclass.talklive.app.bean.RecordVideoInfo;
import com.qianclass.talklive.app.bean.TextWhiteBoardBean;
import com.qianclass.talklive.app.bean.VideoBody;
import com.qianclass.talklive.app.bean.WhiteBoardBean;
import com.qianclass.talklive.app.fragment.VideoTextureFragment;
import com.qianclass.talklive.app.utils.ColorUtils;
import com.qianclass.talklive.app.utils.Constant;
import com.qianclass.talklive.app.utils.Info;
import com.qianclass.talklive.app.utils.LogUtil;
import com.qianclass.talklive.app.utils.VerificationKeyUtils;
import com.qianclass.talklive.app.view.Graffiti.GraffitiView;
import com.qianclass.talklive.app.view.VerticalSeekBar;

import org.json.JSONArray;
import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by Administrator on 2018/1/19.
 */

public class RecordPlayerActivity extends Activity implements View.OnClickListener {

    private static final int DOWNLOADIMGSUCCESS = 10000;

    private FrameLayout mFlWBContainer;
    private FrameLayout mFlAnchorContainer;
    private FrameLayout mFlAudienceContainer;
    private Gson mGson;
    private ImageView mIvNoData;
    private LinearLayout mLlContainer;
    private String mRecordDateTime;
    private TextView mTvVideoDuration;
    private TextView mTvVideoProgress;
    private SeekBar mSeekBar;
    private PLMediaPlayer mTeacherPLMediaPlayer;
    private PLMediaPlayer mStudentPLMediaPlayer;
    private LinearLayout mLlVideoProgress;
    private ProgressBar mPbWhiteboard;
    private GraffitiView mGraffitiView;
    private List<VideoBody> mChatsList;
    private ListView mLvChat;
    private List<RecordIMInfo.MessageBean> mWhiteboardList;
    private List<RecordIMInfo.MessageBean> mWBProcessedList;
    private TextView mTvVideoName;
    private ImageView mIvVideoBack;
    private ImageView mIvVideoPlayPause;
    private ImageView mIvVideoVolume;
    private VideoTextureFragment mTeacherVTextureFragment;
    private VideoTextureFragment mStudentVTextureFragment;
    private boolean isVideoPlaying;
    private VerticalSeekBar mVseekbarVolume;
    private boolean isVolumeShow;
    private AudioManager mAudioManager;
    private VolumeReceiver mVolumeReceiver;
    private TextView mTvWBPage;
    private int mWBFileid;
    private String mWBFiledir;
    private int mWBPagenum;
    private int mWBCurrentpage;
    private List<FileInfo> mFileInfoList;
    private boolean isActivityBackStack;
    private List<RecordVideoInfo.VideoBean> mTeacherVideoList;
    private List<RecordVideoInfo.VideoBean> mStudentVideoList;

    public static void JumpInto(Context context, String roomID, String roomName) {
        Intent intent = new Intent(context, RecordPlayerActivity.class);
        intent.putExtra("roomID", roomID);
        intent.putExtra("roomName", roomName);
        context.startActivity(intent);
    }

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case DOWNLOADIMGSUCCESS:
                    //课件下载成功
                    Bitmap bitmap = (Bitmap) msg.obj;
                    mPbWhiteboard.setVisibility(View.GONE);

                    if (bitmap != null) {
                        createWhiteBoard(bitmap);
                    }
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 创建教材图片
     * @param bitmap
     */
    private void createWhiteBoard(Bitmap bitmap) {
        mGraffitiView = null;
        mFlWBContainer.removeAllViews();

        mGraffitiView = new GraffitiView(this, bitmap, true, new GraffitiView.GraffitiListener() {
            @Override
            public void onError(int i, String msg) {
                LogUtil.e("createWB", msg);
                Toast.makeText(RecordPlayerActivity.this, msg, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onReady() {
                LogUtil.e("createWB", "sucess");
            }
        });

        mGraffitiView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });

        mFlWBContainer.addView(mGraffitiView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                             WindowManager.LayoutParams.FLAG_FULLSCREEN);

        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        /*平板-手机*/
        setContentView(isTabDevice() ? R.layout.activity_record_player_pad : R.layout.activity_record_player);

        initView();

        initListener();
    }

    @Override
    protected void onStart() {
        super.onStart();

        if (!isActivityBackStack) {
            initData();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        isActivityBackStack = true;
    }

    private void initView() {

        mTvVideoName = (TextView) findViewById(R.id.tv_video_name);
        mIvVideoBack = (ImageView) findViewById(R.id.iv_video_back);

        mLlContainer = (LinearLayout) findViewById(R.id.ll_container);
        mIvNoData = (ImageView) findViewById(R.id.iv_no_data);

        mFlWBContainer = (FrameLayout) findViewById(R.id.fl_wb_container);
        mPbWhiteboard = (ProgressBar) findViewById(R.id.pb_whiteboard);
        mTvWBPage = (TextView) findViewById(R.id.tv_wb_page);

        mFlAnchorContainer = (FrameLayout) findViewById(R.id.fl_anchor_container);
        mFlAudienceContainer = (FrameLayout) findViewById(R.id.fl_audience_container);

        mLvChat = (ListView) findViewById(R.id.lv_chat);

        mLlVideoProgress = (LinearLayout) findViewById(R.id.ll_video_progress);
        mTvVideoDuration = (TextView) findViewById(R.id.tv_video_duration);
        mTvVideoProgress = (TextView) findViewById(R.id.tv_video_progress);
        mSeekBar = (SeekBar) findViewById(R.id.seekbar);
        mIvVideoPlayPause = (ImageView) findViewById(R.id.iv_video_play_pause);
        mIvVideoVolume = (ImageView) findViewById(R.id.iv_video_volume);
        mVseekbarVolume = (VerticalSeekBar) findViewById(R.id.vseekbar_volume);
    }

    private void initListener() {

        mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                //LogUtil.e("seekbar", "progress:" + progress);
                /*if (isDragSeekBar) {
                    LogUtil.e("seekbar", "Dragprogress:" + progress);
                    if (mStudentVTextureFragment != null) {
                        mStudentVTextureFragment.seekTo(progress);
                    }

                    if (mTeacherVTextureFragment != null) {
                        mTeacherVTextureFragment.seekTo(progress);
                        updateProgress(progress);
                    }

                    changeWBInfo();
                }*/
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                LogUtil.e("seekbar", "start");
                mHandler.removeCallbacks(mRunnable);
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                LogUtil.e("seekbar", "stop");
                int progress = seekBar.getProgress();
                LogUtil.e("seekbar", "jump:" + progress);
                if (mStudentVTextureFragment != null) {
                    mStudentVTextureFragment.seekTo(progress);
                }

                if (mTeacherVTextureFragment != null) {
                    mTeacherVTextureFragment.seekTo(progress);
                }

                //changeWBInfo();

                if (isVideoPlaying) {
                    mHandler.postDelayed(mRunnable, 200);
                }
            }
        });

        mVseekbarVolume.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                updateVolume(progress);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        mIvVideoBack.setOnClickListener(this);
        mIvVideoPlayPause.setOnClickListener(this);
        mIvVideoVolume.setOnClickListener(this);
    }

    private void initData() {
        String roomID = getIntent().getStringExtra("roomID");
        String roomName = getIntent().getStringExtra("roomName");

        mTvVideoName.setText(roomName);

        getRecordVideoInfo(roomID);
        getRecordIMInfo(roomID);

        mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
        int maxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        mVseekbarVolume.setMax(maxVolume);
        int volume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        updateVolume(volume);

        registerVolumeReceiver();

        mFileInfoList = new ArrayList<>();
    }

    /**
     * 注册音量发生变化时的广播
     */
    private void registerVolumeReceiver(){
        mVolumeReceiver = new VolumeReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.media.VOLUME_CHANGED_ACTION");
        registerReceiver(mVolumeReceiver, filter);
    }

    private void unRegisterVolumeReceiver(){
        if (mVolumeReceiver != null) {
            unregisterReceiver(mVolumeReceiver);
            mVolumeReceiver = null;
        }
    }

    /**
     * 音量变化的广播接收器
     * @author long
     */
    private class VolumeReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            //如果音量发生变化则更改seekbar的位置
            if(intent.getAction().equals("android.media.VOLUME_CHANGED_ACTION")){
                int currVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);// 当前的媒体音量
                updateVolume(currVolume);
            }
        }
    }

    /**
     * 更新音量
     * @param volume
     */
    private void updateVolume(int volume) {
        mVseekbarVolume.setProgress(volume);
        //更新音量值
        mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volume, 0);//flag 0 默认不显示系统控制栏  1 显示系统音量控制
    }

    /**
     * 是否是平板设备
     * @return
     */
    private boolean isTabDevice() {
        return (getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;
    }

    /**
     * 获取录像的IM信息
     * @param roomID
     */
    private void getRecordIMInfo(String roomID) {
        VerificationKeyUtils keyUtils = new VerificationKeyUtils();
        String VerificationKey = keyUtils.getVerificationKey(TalkApplication.getMechanismId());
        HttpUtils httpUtils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.addBodyParameter("Version", Info.APIVERSION);
        params.addBodyParameter("RoomID", roomID);
        params.addBodyParameter("VerificationKey", VerificationKey);


        httpUtils.send(HttpRequest.HttpMethod.POST, Constant.getRecordIMInfo(), params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                try {
                    LogUtil.e("GetIMInfo", "IMInfo:" + responseInfo.result.toString());
                    if (mGson == null) {
                        mGson = new Gson();
                    }

                    RecordIMInfo recordIMInfo = mGson.fromJson(responseInfo.result, RecordIMInfo.class);
                    if (recordIMInfo.isResult()) {

                        mChatsList = new ArrayList<VideoBody>();
                        mWhiteboardList = new ArrayList<RecordIMInfo.MessageBean>();
                        mWBProcessedList = new ArrayList<RecordIMInfo.MessageBean>();
                        for (RecordIMInfo.MessageBean messageBean : recordIMInfo.getMessage()) {
                            String dateTime = messageBean.getDateTime();

                            String messageText = new String(Base64.decode(messageBean.getMessageText(), Base64.DEFAULT), "utf-8").trim();
                            LogUtil.e("messageText", messageText);

                            if (messageText.startsWith("{")) {
                                parseMessage(dateTime, messageText);
                            } else {
                                String[] strs = messageText.split(":");
                                if (strs.length == 2) {
                                    mChatsList.add(new VideoBody(strs[0], strs[1], dateTime, 4));
                                }
                            }
                        }

                        LogUtil.e("processWhiteBoard", "size:" + mWhiteboardList.size());
                        ChatHistoryAdapter chatHistoryAdapter = new ChatHistoryAdapter(RecordPlayerActivity.this, mChatsList);
                        mLvChat.setAdapter(chatHistoryAdapter);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                LogUtil.e("GetIMInfo", s);
            }
        });
    }

    private void parseMessage(String dateTime, String messageText) {
        try {
            JSONObject jsonObject = new JSONObject(messageText);
            if (jsonObject == null) {
                return;
            } else {
                String message = jsonObject.getString("message");
                JSONObject messageObject = new JSONObject(message);
                String msgType = messageObject.getString("type");

                if (msgType.equals("whiteboard")) {
                    long time = dateStringToLong(dateTime, "yyyy/MM/dd HH:mm:ss");
                    LogUtil.e("date", "date:" + time);

                    String whiteboard = messageObject.getString("whiteboard");
                    RecordIMInfo.MessageBean messageBean = new RecordIMInfo.MessageBean();
                    messageBean.setDateTime(String.valueOf(time));
                    messageBean.setMessageText(whiteboard);
                    mWhiteboardList.add(messageBean);
                }else if(msgType.equals("chat")){
                    String body = messageObject.getString("body");
                    processChatInfo(dateTime, body);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 处理录像中聊天信息
     * @param body
     */
    private void processChatInfo(String dateTime, String body) {

        VideoBody videoBody = mGson.fromJson(body, VideoBody.class);
        if (videoBody.getUsertype() == 4) {
            videoBody.setUser(getString(R.string.system_msg));
        }
        videoBody.setTime(dateTime);
        mChatsList.add(videoBody);
    }

    /**
     * 处理录像中白板信息
     * @param whiteboard
     */
    private void processWBInfo(String whiteboard) {
        try {
            LogUtil.e("processWhiteBoard", whiteboard);
            JSONObject whiteboardObject = new JSONObject(whiteboard);
            String subcommand = whiteboardObject.getString("subcommand");

            if (subcommand.equals("openfile")) {
                //打开白板文件
                mWBFileid = whiteboardObject.getInt("fileid");
                mWBFiledir = whiteboardObject.getString("filedir");
                mWBPagenum = whiteboardObject.getInt("pagenum");
                String filename = whiteboardObject.getString("filename");
                mWBCurrentpage = 1;
                loadWhiteBoard(mWBFileid, mWBCurrentpage, mWBPagenum, mWBFiledir, filename);
            } else if (subcommand.equals("pageturn")) {
                //课件翻页
                mWBFileid = whiteboardObject.getInt("fileid");
                mWBFiledir = whiteboardObject.getString("filedir");
                if (whiteboardObject.has("pagenum")) {
                    mWBPagenum = whiteboardObject.getInt("pagenum");
                }
                mWBCurrentpage = whiteboardObject.getInt("currentpage");

                loadWhiteBoard(mWBFileid, mWBCurrentpage, mWBPagenum, mWBFiledir, "");
            } else if (subcommand.equals("addobject") && whiteboardObject.has("objtype")) {
                //添加涂鸦笔迹
                String objtype = whiteboardObject.getString("objtype");
                if (objtype.equals("text")) {
                    mGson.fromJson(whiteboard, TextWhiteBoardBean.MessageBean.WhiteboardBean.class);
                }else{
                    WhiteBoardBean whiteBoardBean = mGson.fromJson(whiteboard, WhiteBoardBean.class);
                    if (mGraffitiView != null) {
                        mGraffitiView.storeGraffitiLineData(whiteBoardBean);
                        doPaintGraffiti(whiteBoardBean);
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 加载白板
     * @param fileId
     * @param currentPage
     * @param pageNum
     * @param fileDir
     * @param fileName
     */
    private void loadWhiteBoard(int fileId, int currentPage, int pageNum, String fileDir, String fileName){
        boolean isFileExist = false;
        for (FileInfo fileInfo : mFileInfoList) {
            if(fileId == fileInfo.getFileID()){
                isFileExist = true;
            }
        }
        if(!isFileExist){
            FileInfo fileInfo = new FileInfo(fileId, pageNum + "", fileName, fileDir);
            mFileInfoList.add(fileInfo);
        }

        if(fileName.contains(".mp3") || fileName.contains(".wav") || fileName.contains(".wma")){
            fileDir = Constant.WHITEBOARDFILEDIR;
        }

        String textBookUrl = Constant.getDocUrl() + fileDir + "/" + currentPage + ".jpg";
        loadImageBitmap(textBookUrl);
        mTvWBPage.setVisibility(View.VISIBLE);
        mTvWBPage.setText(currentPage + "/" + pageNum);
    }

    private void doPaintGraffiti(WhiteBoardBean whiteBoardBean) {
        //轨迹编号id
        int objid = whiteBoardBean.getObjid();
        //画线
        if (whiteBoardBean.getObjtype().equals("pen")) {
            float stratX = whiteBoardBean.getObjdata().get(0).getX();
            float stratY = whiteBoardBean.getObjdata().get(0).getY();
            int color = Color.parseColor(ColorUtils.chageColor(whiteBoardBean.getColour()));
            LogUtil.i("画笔颜色", "color = " + color);
            float paintSize = whiteBoardBean.getLinewidth() + 0.5f;
            mGraffitiView.setPaintSizePost(paintSize);
            int size = whiteBoardBean.getObjdata().size();
            for (int i = 0; i < size; i++) {
                float x = whiteBoardBean.getObjdata().get(i).getX();
                float y = whiteBoardBean.getObjdata().get(i).getY();
                mGraffitiView.setDrawPaint(stratX, stratY, x, y, size, i, color, paintSize, objid);
                stratX = x;
                stratY = y;
            }
        }
        // 画矩形
        else if (whiteBoardBean.getShapetype().equals("emptyrect")) {
            int color = Color.parseColor(ColorUtils.chageColor(whiteBoardBean.getColour()));
            float left = whiteBoardBean.getRect().getLeft();
            float top = whiteBoardBean.getRect().getTop();
            float right = whiteBoardBean.getRect().getRight();
            float bottom = whiteBoardBean.getRect().getBottom();
            mGraffitiView.setDrawPaintEmptyRect(left, top, right, bottom, color, "emptyrect", null, objid);

        }
        // 画圆形
        else if (whiteBoardBean.getShapetype().equals("emptyellipse")) {
            int color = Color.parseColor(ColorUtils.chageColor(whiteBoardBean.getColour()));
            float left = whiteBoardBean.getRect().getLeft();
            float top = whiteBoardBean.getRect().getTop();
            float right = whiteBoardBean.getRect().getRight();
            float bottom = whiteBoardBean.getRect().getBottom();
            mGraffitiView.setDrawPaintEmptyRect(left, top, right, bottom, color, "emptyellipse", null, objid);

        }
        // 画直线
        else if (whiteBoardBean.getShapetype().equals("line")) {
            int color = Color.parseColor(ColorUtils.chageColor(whiteBoardBean.getColour()));
            float left = whiteBoardBean.getRect().getLeft();
            float top = whiteBoardBean.getRect().getTop();
            float right = whiteBoardBean.getRect().getRight();
            float bottom = whiteBoardBean.getRect().getBottom();
            mGraffitiView.setDrawPaintEmptyRect(left, top, right, bottom, color, "line", null, objid);
        }
    }

    private void loadImageBitmap(final String url) {
        try {
            LogUtil.i("downloadIMG", "url:" + url);
            if (url == null) {
                return;
            }
            /*if(!url.contains("null")) {
                ThreadUtils.runOnMainThread(new Runnable() {
                    @Override
                    public void run() {
                        mPbWhiteboard.setVisibility(View.VISIBLE);
                    }
                });
            }*/

            OkGo.get(url)//
                .tag(this)//
                .execute(new BitmapCallback() {
                    @Override
                    public void onSuccess(Bitmap bitmap, Call call, Response response) {
                        LogUtil.i("downloadIMG", "success");
                        Message obtain = Message.obtain();
                        obtain.obj = bitmap;
                        obtain.what = DOWNLOADIMGSUCCESS;
                        mHandler.sendMessage(obtain);
                    }

                    @Override
                    public void onError(Call call, Response response, final Exception e) {
                        super.onError(call, response, e);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(RecordPlayerActivity.this, e.getMessage() + "||" + url, Toast.LENGTH_SHORT).show();
                                LogUtil.e("downloadIMG", e.getMessage() + "||" + url);
                                mPbWhiteboard.setVisibility(View.GONE);
                            }
                        });
                    }
                });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取录像视频信息
     * @param roomID
     */
    private void getRecordVideoInfo(String roomID) {
        VerificationKeyUtils keyUtils = new VerificationKeyUtils();
        String VerificationKey = keyUtils.getVerificationKey(TalkApplication.getMechanismId());
        HttpUtils httpUtils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.addBodyParameter("Version", Info.APIVERSION);
        params.addBodyParameter("RoomID", roomID);
        params.addBodyParameter("VerificationKey", VerificationKey);

        httpUtils.send(HttpRequest.HttpMethod.POST, Constant.getRecordVideoInfo(), params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                LogUtil.e("GetVideoInfo", "VideoInfo:" + responseInfo.result.toString());
                if (mGson == null) {
                    mGson = new Gson();
                }
                RecordVideoInfo recordVideoInfo = mGson.fromJson(responseInfo.result,
                                                                 RecordVideoInfo.class);

                mTeacherVideoList = new ArrayList<>();
                mStudentVideoList = new ArrayList<>();
                if (recordVideoInfo.isResult()) {
                    if (recordVideoInfo.getVideo().size() == 0) {
                        mIvNoData.setVisibility(View.VISIBLE);
                        mLlContainer.setVisibility(View.GONE);
                        mPbWhiteboard.setVisibility(View.GONE);
                    } else {
                        for (RecordVideoInfo.VideoBean videoBean : recordVideoInfo.getVideo()) {

                            mRecordDateTime = videoBean.getRecordDateTime();
                            long time = dateStringToLong(mRecordDateTime, "yyyy/MM/dd HH:mm:ss");

                            if (videoBean.getUserType() == 1) {
                                String teacherVideoUrl = Constant.BASERECORDURL + videoBean.getVideoStream();

                                RecordVideoInfo.VideoBean teacherVideoBean = new RecordVideoInfo.VideoBean();
                                teacherVideoBean.setVideoStream(teacherVideoUrl);
                                teacherVideoBean.setRecordDateTime(String.valueOf(time));
                                teacherVideoBean.setUserType(1);
                                mTeacherVideoList.add(teacherVideoBean);

                                //playVideoStream(videoBean.getUserType(), teacherVideoUrl, mFlAnchorContainer);
                            } else if (videoBean.getUserType() == 2) {
                                String studentVideoUrl = Constant.BASERECORDURL + videoBean.getVideoStream();

                                RecordVideoInfo.VideoBean studentVideoBean = new RecordVideoInfo.VideoBean();
                                studentVideoBean.setVideoStream(studentVideoUrl);
                                studentVideoBean.setRecordDateTime(String.valueOf(time));
                                studentVideoBean.setUserType(2);
                                mStudentVideoList.add(studentVideoBean);

                                //playVideoStream(videoBean.getUserType(), studentVideoUrl, mFlAudienceContainer);
                            }
                        }

                        getVideoDuration();

                        if (mTeacherVideoList.size() > 0) {
                            RecordVideoInfo.VideoBean tVideoBean = mTeacherVideoList.get(0);
                            RecordVideoInfo.VideoBean sVideoBean = mStudentVideoList.get(0);
                            playVideoStream(tVideoBean.getUserType(), tVideoBean.getVideoStream(), mFlAnchorContainer);
                            playVideoStream(sVideoBean.getUserType(), sVideoBean.getVideoStream(), mFlAudienceContainer);
                        }
                    }
                } else {
                    mIvNoData.setVisibility(View.VISIBLE);
                    mLlContainer.setVisibility(View.GONE);
                    mPbWhiteboard.setVisibility(View.GONE);
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                LogUtil.e("GetVideoInfo", s);
            }
        });
    }

    /**
     * 获取视频时长
     */
    private void getVideoDuration() {
        for (RecordVideoInfo.VideoBean videoBean : mTeacherVideoList) {
            String videoStream = videoBean.getVideoStream();

            HttpUtils httpUtils = new HttpUtils();
            httpUtils.send(HttpRequest.HttpMethod.GET, videoStream + "?avinfo", new RequestCallBack<String>() {
                @Override
                public void onSuccess(ResponseInfo<String> responseInfo) {
                    try {
                        JSONObject jsonObject = new JSONObject(responseInfo.result);
                        JSONArray streams = jsonObject.getJSONArray("streams");
                        JSONObject streamsObject = new JSONObject(streams.get(0).toString());
                        String duration = streamsObject.getString("duration");

                        LogUtil.e("stream", "duration:" + duration);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(HttpException e, String s) {

                }
            });
        }
    }

    public long dateStringToLong(String date, String format){
        long time = 0;
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat(format);
            Date parse = dateFormat.parse(date);
            time = parse.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return time;
    }

    /**
     * 播放录像视频
     * @param userType
     * @param url
     * @param frameLayout
     */
    public void playVideoStream(final int userType, String url, FrameLayout frameLayout){
        final VideoTextureFragment videoTextureFragment = new VideoTextureFragment();
        Bundle bundle = new Bundle();
        bundle.putString("videopath", url);
        videoTextureFragment.setArguments(bundle);
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(frameLayout.getId(), videoTextureFragment, "videoStream");
        fragmentTransaction.commit();

        /**
         * 视频的进度显示及控制以老师视频为准
         */
        videoTextureFragment.setOnPreparedListener(new VideoTextureFragment.OnVideoPreparedListener() {
            @Override
            public void onVideoPrepared(PLMediaPlayer plMediaPlayer) {
                if (userType == 1) {
                    mTeacherVTextureFragment = videoTextureFragment;
                    mTeacherPLMediaPlayer = plMediaPlayer;
                    long duration = plMediaPlayer.getDuration();
                    String formatDuration = timeFormat.format(duration);

                    mLlVideoProgress.setVisibility(View.VISIBLE);
                    mTvVideoDuration.setText(formatDuration);
                    mSeekBar.setMax((int) duration);
                    mIvVideoPlayPause.setImageResource(R.drawable.selector_music_pause);
                    isVideoPlaying = true;

                    mHandler.post(mRunnable);
                } else {
                    mStudentVTextureFragment = videoTextureFragment;
                    mStudentPLMediaPlayer = plMediaPlayer;
                }
            }
        });

        videoTextureFragment.setOnCompletionListener(new VideoTextureFragment.OnVideoCompletionListener() {
            @Override
            public void onVideoCompletion(PLMediaPlayer plMediaPlayer) {
                if (userType == 1) {
                    mIvVideoPlayPause.setImageResource(R.drawable.selector_music_play);
                    isVideoPlaying = false;
                    mSeekBar.setProgress(0);
                    mTvVideoProgress.setText("00:00");
                    mHandler.removeCallbacks(mRunnable);
                }
            }
        });
    }

    public void updateProgress(int currentPosition){
        String formatCurrentPosition = timeFormat.format(currentPosition);
        mTvVideoProgress.setText(formatCurrentPosition);
        mSeekBar.setProgress(currentPosition);
    }

    private SimpleDateFormat timeFormat = new SimpleDateFormat("mm:ss");

    private Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            try {
                long currentPosition =  mTeacherPLMediaPlayer.getCurrentPosition();
                long startRecordTime = dateStringToLong(mRecordDateTime, "yyyy/MM/dd HH:mm:ss");

                int WBProcessedSize = mWBProcessedList.size();

                for (int i = 0; i < mWhiteboardList.size(); i++) {
                    RecordIMInfo.MessageBean messageBean = mWhiteboardList.get(i);
                    long dateTime = Long.parseLong(messageBean.getDateTime());

                    if (dateTime <= startRecordTime + currentPosition) {
                        mWBProcessedList.add(messageBean);
                        mWhiteboardList.remove(messageBean);
                    }
                }

                for (int j = mWBProcessedList.size() - 1; j >= 0; j--) {
                    RecordIMInfo.MessageBean messageBean = mWBProcessedList.get(j);
                    long dateTime = Long.parseLong(messageBean.getDateTime());
                    if (dateTime > startRecordTime + currentPosition) {
                        mWhiteboardList.add(0, messageBean);
                        mWBProcessedList.remove(messageBean);
                    }
                }

                if (mWBProcessedList.size() > 0 && mWBProcessedList.size() != WBProcessedSize) {
                    LogUtil.e("WBList", "mWhiteboardList:" + mWhiteboardList.size() + ";mWBProcessedList:" + mWBProcessedList.size());
                    int lastPageIndex = 0;
                    for (int n = mWBProcessedList.size() - 1; n >= 0; n--) {
                        String messageText = mWBProcessedList.get(n).getMessageText();
                        JSONObject whiteboardObject = new JSONObject(messageText);
                        String subcommand = whiteboardObject.getString("subcommand");
                        int fileid = whiteboardObject.getInt("fileid");
                        int currentpage = whiteboardObject.getInt("currentpage");

                        if(subcommand.equals("openfile") || subcommand.equals("pageturn")){
                            LogUtil.e("WBList", "WB:" + n);
                            if(fileid != mWBFileid || currentpage != mWBCurrentpage){
                                processWBInfo(messageText);
                            }
                            lastPageIndex = n;
                            break;
                        }
                    }

                    for (int m = mWBProcessedList.size() - 1; m > lastPageIndex; m--) {
                        LogUtil.e("WBList", "m:" + m);
                        String messageText = mWBProcessedList.get(m).getMessageText();
                        processWBInfo(messageText);
                    }
                }

                updateProgress((int) currentPosition);
                mHandler.postDelayed(mRunnable, 500);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    @Override
    protected void onDestroy() {
        mHandler.removeCallbacks(mRunnable);
        unRegisterVolumeReceiver();
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_video_back:
                mHandler.removeCallbacks(mRunnable);
                if (mTeacherVTextureFragment != null) {
                    mTeacherVTextureFragment.stopVideoStream();
                }
                if (mStudentVTextureFragment != null) {
                    mStudentVTextureFragment.stopVideoStream();
                }
                finish();
                break;

            case R.id.iv_video_play_pause:
                isVideoPlaying = !isVideoPlaying;
                playOrPauseVideo(isVideoPlaying);
                break;

            case R.id.iv_video_volume:
                showVolume();
                break;
        }
    }

    private void showVolume() {
        isVolumeShow = !isVolumeShow;
        mVseekbarVolume.setVisibility(isVolumeShow ? View.VISIBLE : View.GONE);
    }

    private void playOrPauseVideo(boolean play) {
        mIvVideoPlayPause.setImageResource(play ? R.drawable.selector_music_pause : R.drawable.selector_music_play);
        if (mTeacherVTextureFragment != null) {
            mTeacherVTextureFragment.playOrPauseVideo(play);
            if (play) {
                mHandler.postDelayed(mRunnable, 200);
            } else {
                mHandler.removeCallbacks(mRunnable);
            }
        }

        if (mStudentVTextureFragment != null) {
            mStudentVTextureFragment.playOrPauseVideo(play);
        }
    }
}
